import time
import requests
from utils.myjwt import MyJwt
from flask import Blueprint, jsonify, make_response, redirect
from utils.myjwt import MyJwt
from db import db
import datetime,random
from utils.captcha.captcha import Captcha
from utils.myredis import r
from utils.smscode import SmsCode
from utils.myjwt import MyJwt
from flask_restful import reqparse,Resource,Api
from flask import current_app as app,request
from job.tasks.mytask import send_message
import json
user_blue = Blueprint('user_blue',__name__)
api=Api(user_blue)
@user_blue.route("/test")
def test():
    str = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')+"   "+request.path+"   error"
    try:
        sql = "insert into user values(0,'aa22222','abc')"
        db.update(sql)
        db.commit()
        app.logger.info(str+'加入用户成功')
    except:
        app.logger.error(str+'失败')
        db.rollback()

    return 'ok234234'

# 发送验证码视图
class SmsCodes(Resource):
    def post(self):
        # 获取手机号
        req=reqparse.RequestParser()
        req.add_argument('phone')
        args=req.parse_args()
        # 有效性验证
        rule=r'^1[3-9][0-9]{9}$'
        if not rule:
            return jsonify({
                'code':400,
                'msg':'手机号格式不匹配'
            })
        # 调用短信平台发送验证码
        code=random.randint(100000,999999)
        sdk=SmsCode().send(args['phone'],code)
        # 发送失败（重试3次）
        if not sdk:
            return jsonify({
                'code':400,
                'msg':'发送失败'
            })
        return jsonify({
                'code':200,
                'msg':'验证发送成功',
                'data':code
            })
api.add_resource(SmsCodes,'/sms')

# 登录视图
class LoginView(Resource):
    def post(self):
        req=reqparse.RequestParser()
        req.add_argument('phone')
        req.add_argument('code')
        args=req.parse_args()
        if not args['phone']:
            return jsonify({
                'code':400,
                'msg':'手机号不存在'
            })
        pho="select * from user where phone=%s"%args['phone']
        db.find(pho)
        if not pho:
            # 创建手机号和密码
            a="insert into user(id,phone) values ('1',%s)"%args['phone']
            db.update(a)
            db.commit()
            return jsonify({
                'code':200,
                'msg':'注册成功'
            })
        pho = "select * from user where phone=%s" % args['phone']
        db.find(pho)

        token=MyJwt().jwt_encode({
            'phone':args['phone']
        })
        return jsonify({
            'code':200,
            'msg':'登录成功',
            'token':token
        })
api.add_resource(LoginView,'/login')

# 生成图片验证码
@user_blue.route('/create_imagecode/')
def create_imagecode():
    uuid=request.args.get('uuid')
    name,text,image=Captcha().generate_captcha()
    res=make_response(image)
    res.headers['Content-Type']='image/jpg'
    # 存入redi
    r.set_str(uuid,text)
    return res

@user_blue.route('empMager',methods=['POST','GET'])
def empMager():
    return 'ok'
@user_blue.route('/get_wb')
def get_wb():
    client_id = '3674019597'
    redirect_uri = 'http://127.0.0.1:8000/user/weiboCallback/'
    url = "http://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
    client_id, redirect_uri)

    return jsonify({
        'url': url
    })

@user_blue.route('/weboCallback/')
def weboCallback():
    # 获取code
    code=request.args.get('code')
    # 通过code去获取uid和token
    data={'client_id':'3674019597','client_secret':'7ae99bc0d54ead29fc8d1b9fabd78587',"grant_type":"authorization_code",'redirect_uri':'http://127.0.0.1:8000/user/weiboCallback/','code':code}
    res=requests.post('https://api.weibo.com/oauth2/access_token',data=data)
    result=json.loads(res.text)
    uid=result['uid']
    token=result['access_token']
    #判断数据是否存在
    sql="select user.id,user.name from sf_login as sf left join user on sf,userid=user.id where sf"
    res=db.find(sql)
    if not res:
        # 不存在绑定用户
        return redirect("http://127.0.0.1:8000/#/binduser?uid="+uid+"&token="+token)
    else:
         # 存在获取user
         nowdata=int(time.time())
         data={'data':{"id":res['uid'],'name':res['uname']},'exp':nowdata}
         token=MyJwt().jwt_encode(data)
         # 封装token返回
         return redirect("http://127.0.0.1:8080/#/sflogin?userid=" + res['uid'] + "&name" + res['uname'] + "token" + token)


@ user_blue.route('/weibobind',methods=['post'])
def weibobind():
    data=json.loads(request.data)
    # 写入用户表
    sql="select * from user where phone='%s'"%(data['mobile'])
    user=db.find()
    lasrid=user['id']
    if not user:
        insertsql="insert into user(name,phone) values('%s','%s')"%(data['mobile'],data['mobile'])
        lastid=db.update(insertsql)
    # 查的新写的id
    # 写入第三方登录表
    sansql="insert into sf_login(userid,u_from,uid,token) values(%d,'%s','%s','%s')"%(lastid,'weibo')
    db.update(sansql)
    db.commit() 
    # 生成token返回
    nowdata=int(time.time())
    data={'data':{"id":lastid,'name':data['mobile'],'exp':nowdata}}
    token=MyJwt().jwt_encode(data)
    return jsonify({"code":200,"user":{"id":lastid,'name':data['mobile']},'token':token})

